package mq.demo.priority;

import cn.itlaobing.Util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mifei
 * @create 2018年04月12日
 **/
public class Recv {
    private static String exchange_name = "priority_direct";
    private static String queueName = "mf_test_simple";

    public static void priorityRecv() throws Exception {
        Connection conn = ConnectionUtil.getConnection();
        final Channel channel = conn.createChannel();
        channel.exchangeDeclare(exchange_name, "direct");
        //设置队列的优先级，消息的优先级大于队列的优先级，以较小值为准(例如：队列优先级5、消息优先级8，消息实际优先级为5)
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("x-max-priority", 10);//队列优先级只能声明一次，不可改变(涉及到硬盘、内存存储方式)
        channel.queueDeclare(queueName, false, false, false, args);
        channel.queueBind(queueName, exchange_name, "");
        channel.basicQos(1);//需要开启手动应答模式，否则无效
        channel.basicConsume(queueName, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body);
                System.out.println(properties.getPriority() + ":priority Received :'" + message + "' done");
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        priorityRecv();
    }
}
